import http from '@/common/interface.js'
import config from '@/config.js'
import store from '@/store/index.js'
import Vue from 'vue'
import CryptoJS from "crypto-js/crypto-js";
//设置baseUrl
http.config.baseUrl = config.host
//设置请求前拦截器
http.interceptor.request = (config,upload) => {

	if(needEncrypt(config)){//加密接口入参需先加密
		config.data = {encryptData:Vue.prototype.$utils.encryptDes(config.data),encrypt:1}
		//添加通用参数
		config.header = buildHeader(config.header, config.data, config.url)
		upload ? uni.uploadFile(config) : uni.request(config);

	}else{
		//添加通用参数
		config.header = buildHeader(config.header, config.data, config.url)
		upload ? uni.uploadFile(config) : uni.request(config);
	}
}

//设置请求结束后拦截器
http.interceptor.response = (response, resolve, reject) => {
    //判断返回状态 执行相应操作
	let result = response.data||response;//防止有的接口未返回data
	if(result.encryptData){//加密接口需先解密
		dealResponse(result,response, resolve, reject)
	}else{
		dealResponse(result,response, resolve, reject)
	}
}

/**
 * 导出接口功能，为了兼容之前的api写法。
 */
export default {
	mgHttp(url, data, type = "api", loading = true, completeFn, errorToast = true,responseType) {
		if (type == 'api') {
			return http.post(url, data, {
				loading,
				completeFn,
				errorToast,
				responseType
			})
		} else if (type == 'get') {
			return http.get(url, data, {
				loading,
				completeFn,
				errorToast
			})
		} else if (type == 'uploadImg') {
			return http.upload(url, data, {
				loading,
				completeFn,
				errorToast
			})
		}
	},
	upLoadVideo({
		url,
		data,
		success,
		formData,
		fail
	}) {
		const _config = {}
		_config.url = config.host + url
		_config.filePath = data
		_config.name = 'file'
		_config.formData = formData
		_config.header = buildHeader({}, data, url)
		_config.success = (res) => {
			let result = res.data;
			if (typeof(result) == 'string') {
				try {
					result = JSON.parse(result);
				} catch (e) {}
			}
			if (result.code == '0000') {
				success ? success(result) : ''
			} else {
				const msg = res.msg || res.message || res.data.message
				msg && uni.showToast({
					title: msg,
					icon: 'none'
				})
				fail ? fail(res) : ''
			}
		}
		_config.fail = (err) => {
			const msg = err.msg || err.message || err.data.message
			msg && uni.showToast({
				title: msg,
				icon: 'none'
			})
			fail ? fail(err) : ''
		}
		return uni.uploadFile(_config)
	}
}

// 浏览器信息。只拿一次。
const bower = getBrowserBrand()
function buildHeader(header, data, url) {
	const mgHeader = {
		
	}
	if (store.state.token) mgHeader['Authorization'] = store.state.token
	return Object.assign(header, mgHeader)
}

/**
 * 获取浏览器品牌
 */
function getBrowserBrand() {
	const rules = [
		["MicroMessenger", "MicroMessenger/([\\d.]+)"],
		["QQ", "QQ/([\\d.]+)"],
		["QQBrowser", "QQBrowser/([\\d.]+)"],
		["UCBrowser", "UCBrowser/([\\d.]+)"],
		["BaiduBrowser", "baidubrowser/([\\d.]+)"],
		["Maxthon", "Maxthon/([\\d.]+)"],
		["IE", "MSIE ([\\d.]+)|Trident/7.0;.*rv:([\\d.]+)"],
		["Edge", "Edge/([\\d.]+)"],
		["Chrome", "Chrome/([\\d.]+)"],
		["Firefox", "Firefox/([\\d.]+)"],
		["Opera", "Opera/([\\d.]+)"],
		["Safari", "Safari/([\\d.]+)"],
		["Migudm", "migudm/([\\d.]+)"],
		["Miguvideo", "miguvideo/([\\d.]+)"],
	]
	const brower = {}
	let ua = ''
	/*  #ifdef H5 */
	ua = navigator.userAgent.toLowerCase();
	/*  #endif  */
	if (!ua) {
		const systemInfo = uni.getSystemInfoSync();
		brower.brand = 'MP-WEIXIN'
		brower.version = systemInfo.version;
		return brower
	}
	for (var i = 0; i < rules.length; i++) {
		var browserRule = rules[i];
		var match = (new RegExp(browserRule[1], 'i')).exec(ua);
		if (match) {
			brower.brand = browserRule[0]
			brower.version = match[1] || match[2];
			break
		}
	}
	if (brower.brand) return brower
	brower.brand = 'unknown'
	brower.version = 'unknown';
	return brower;
}
/**
 * 判读接口是否需要加密
 * @param {Object} mConfig
 */
function needEncrypt(mConfig){
	const encryptUrl = ['user/address/update','user/address/add','user/getCakeCardSecret','user/bindingCakeCard']//需要加密入参的接口
	let keyUrl = mConfig.url.replace(mConfig.baseUrl,'')
	if(encryptUrl.indexOf(keyUrl)>-1){
		return true
	}else{
		return false
	}
}
/**
 * 处理请求返回结果
 * @param {Object} result
 * @param {Object} response
 * @param {Object} resolve
 * @param {Object} reject
 */
function dealResponse(result,response, resolve, reject){
	if (typeof(result) == 'string') {
		try {
			result = JSON.parse(result);
		} catch (e) {}
	}
	let statusCode = response.statusCode
	if (statusCode == 200) {
		if (result.code == "200" || result.code == "21003") {
			resolve(result);
		} else if (response.isAdRes || result.byteLength) { //广告直接返回全部数据
			resolve(response.data);
		} else {
			if (result.code == '21007') {
				// response.errorToast && uni.showToast({
				// 	title: response.msg || response.message || result.message,
				// 	icon: 'none'
				// })
				
				// Vue.prototype.$Login.login({
				// 	tradition: true
				// })
			} else {
				if (response.errorToast && result.code !== -2 && result.code != '1002' && result.code != '1003' && result.code != '2001' && result.code != '2002') {
					const pages = getCurrentPages()
						if(pages.length > 0){
							const page = pages[pages.length-1]
							let customToast = pages[pages.length-1].$vm.$refs
								if(customToast.customToast){
									page.$vm.$refs.customToast.showToast(response.msg || response.message, 4000);
								}else{
										uni.showToast({
											title: response.msg || response.message || result.message,
											icon: 'none',
											duration: 2000
										})
								}
						}else{
							uni.showToast({
								title: response.msg || response.message || result.message,
								icon: 'none',
								duration: 2000
							})
					}
				}
			}
			reject({
				code: result.code,
				success: result.success,
				msg: result.message
			});
		}
	} else if ( statusCode == 401 ) {
		uni.showToast({
			icon: 'none',
			title: '登录失效，请重新登录！'
		})
		setTimeout(() => {
			Vue.prototype.$Login.loginOut(false)
		}, 1000)
	} else {
		if (response.errMsg === 'request:fail') {
			const title = '当前网络不可用，请检查你的网络设置'
			if (!response.isAdRes && response.errorToast) uni.showToast({ title })
			reject({
				code: -2,
				msg: title
			});
		} else {
			let code = result.code || -1;
			let msg = result.message || '网络君累趴了，等会儿再试试...';
			if (!response.isAdRes && response.errorToast) uni.showToast({ title: msg })
			reject({
				code: code,
				msg: msg
			});
		}
	}
}
